/*
 * sampleProgram.c
 *
 *  Created on: Jun 8, 2012
 *      Author: ubuntu
 *
 */
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define BUFSIZE 16384

int main(int argc, char **argv) {

	if (argc != 2) {
		fprintf(stderr, "Usage: %s <string>\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	char * filename = argv[1];

	int fp = open(filename, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR // associar permissoes de leitura e escrita ao novo ficheiro criado
	);
	if (fp == -1) {
		perror("open");
		exit(EXIT_FAILURE);
	}
	int bytes_read;
	int nbytes = 100;
	char * my_string;
	my_string = (char*) malloc(sizeof(char) * (nbytes + 1)); // +1 para o file terminator
	do {
		bytes_read = getline(&my_string, &nbytes, stdin);
		if (bytes_read > 0) {
			// se tem spam virus para o ficheiro
			if (strstr(my_string, "virus")) {

				int bytes_write;
				bytes_write = write(fp, my_string, strlen(my_string));

				if (bytes_write == -1) {
					perror("write");
					exit(EXIT_FAILURE);
				}
			} else
			// devolve para o stdout
			{
				fprintf(stdout, "%s", my_string);
			}
		}
	} while (bytes_read > 0);

	close(fp);

	return EXIT_SUCCESS;
}
